﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace WeChat.AspNet
{
    /// <summary>
    /// 响应类，用于签名验证和xml输出。
    /// </summary>
    public class WeChatResponse
    {
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="token"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        public static bool CheckSignature(string token ,String signature, String timestamp, String nonce)
        {
            var arr = new[] { token, timestamp, nonce };
            // 将token、timestamp、nonce三个参数进行字典序排序  
            Array.Sort(arr);

            var content = new StringBuilder();
            foreach (var t in arr)
            {
                content.Append(t);
            }

            var tmpStr = SHA1_Encrypt(content.ToString());

            // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信  
            return tmpStr != null && tmpStr.Equals(signature);
        }

        /// <summary>
        /// 使用缺省密钥给字符串加密
        /// </summary>
        /// <param name="sourceString"></param>
        /// <returns></returns>
        public static string SHA1_Encrypt(string sourceString)
        {
            byte[] strRes = Encoding.Default.GetBytes(sourceString);
            HashAlgorithm iSha = new SHA1CryptoServiceProvider();
            strRes = iSha.ComputeHash(strRes);
            var enText = new StringBuilder();
            foreach (byte iByte in strRes)
            {
                enText.AppendFormat("{0:x2}", iByte);
            }
            return enText.ToString();
        }
        /// <summary>
        /// 输出xml响应内容。
        /// </summary>
        /// <param name="xmlContent"></param>
        public static void Write(string xmlContent)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(xmlContent);
        }
    }
}